<template>
  <div style="background-color: #f0f3fb; padding: 10px">
    <div style="background-color: #fff; border-radius: 5px; padding: 10px">
      <div style="display: flex">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">基础信息</div>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商品名称:</div>
        <input v-model="spForm.storeName" class="input_class" placeholder="必填，请填写商品名称" />
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商品简介:</div>
        <textarea v-model="spForm.storeInfo" class="textarea_class" placeholder="必填，请写下商品的简介,便于用户了解商品	"></textarea>
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商品价格:</div>
        <input type="digit" v-model="spForm.price" class="input_class" placeholder="必填，商品价格" />
      </div>
      <div style="display: flex; align-items: center">
        <div style="width: 90px">商品照片:</div>
        <div style="margin-top: 15px">
          <!-- 		<div style="border: 1px #00000 dashed; border-radius: 3px; width: 200rpx; height: 200rpx; line-height: 200prx; text-align: center;">
					</div> -->
          <u-upload :fileList="fileList" @afterRead="afterRead" height="200" width="200" @delete="deletePic" name="3" :maxCount="10" :previewFullImage="true">
            <div style="border: 1px #000 dashed; border-radius: 3px; width: 200rpx; height: 200rpx; line-height: 200prx; text-align: center">
              <image :src="images" style="width: 90px; height: 90px"></image>
            </div>
          </u-upload>
        </div>
      </div>
    </div>
    <div style="background-color: #fff; border-radius: 5px; padding: 10px; margin-top: 15px">
      <div style="display: flex; padding: 10px">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">详细信息</div>
      </div>
      <u-cell-group>
        <u-cell size="large" title="商品类别" :value="typeValue1" @click="getType" isLink></u-cell>
        <u-cell size="large" title="是否上架" :value="typeValue" @click="getTypelx" isLink></u-cell>
        <div style="display: flex; align-items: center">
          <div style="width: 90px">返回积分:</div>
          <input type="digit" v-model="spForm.giveIntegral" class="input_class" placeholder="必填，获得返回积分" />
        </div>
        <div style="display: flex; align-items: center">
          <div style="width: 90px">抵扣比例:</div>
          <input min="0" max="1" type="digit" v-model="spForm.canUseIntegral" class="input_class" placeholder="必填，抵扣比例 0.1=10%，0.2=20%  " />
        </div>
        <div style="display: flex; align-items: center">
          <div style="width: 90px">物业补贴抵扣后价格:</div>
          <input v-model="spForm.integralComunityDiscountPrice" disabled class="input_class" placeholder="自动计算（价格-抵扣比例*价格）" />
        </div>
        <div style="display: flex; align-items: center">
          <div style="width: 90px">商品单位:</div>
          <input v-model="spForm.unitName" class="input_class" placeholder="必填，商品单位" />
        </div>
        <div style="display: flex; align-items: center">
          <div style="width: 90px">商品库存:</div>
          <input v-model="spForm.stock" type="number" class="input_class" placeholder="必填，商品库存" />
        </div>
      </u-cell-group>
      <u-picker :show="showType" @cancel="showType = false" :columns="columns" keyName="categoryName" @confirm="getTsType"></u-picker>
    </div>
    <u-button type="primary" @click="addOwner">保存</u-button>
  </div>
</template>

<script>
import { categorylist, productput, merlist, productInfo } from '../../utils/request_sh.js';
export default {
  data() {
    return {
      showType: false,
      columns: [],
      fileList: [],
      typeValue1: '请选择商品类型',
      typeValue: '请选择是否上架',
      xiaoqumingc: '请选择小区',
      isType: '1',
      title: '',
      content: '',
      complaintCategory: '',
      complaintCategorys: '',
      estateId: '',
      fileName: '',
      images: '',
      stasus: '',
      spForm: {
        image: '',
        storeName: '',
        storeInfo: '',
        price: '',
        isShow: '',
        merId: '',
        storeType: '',
        giveIntegral: '',
        canUseIntegral: '',
        stock: '',
        unitName: ''
      }
    };
  },
  onLoad(option) {
    console.log(option);
    this.spId = option.id;
    this.getSpInfo();
  },
  /* 监听价格和比例变化 */
  watch: {
    'spForm.price': 'calculateDiscountedPrice',
    'spForm.canUseIntegral': 'calculateDiscountedPrice'
  },

  methods: {
    /* 根据价格和比例计算折扣后价格 */
    calculateDiscountedPrice() {
      if (this.spForm.canUseIntegral && this.spForm.price) {
        this.spForm.integralComunityDiscountPrice = (this.spForm.price * (1 - this.spForm.canUseIntegral)).toFixed(2);
      } else {
        this.spForm.integralComunityDiscountPrice = 0;
      }
    },
    getSpInfo() {
      productInfo(this.spId).then((res) => {
        this.spForm = res.data;
        this.typeValue1 = res.data.categoryName;
        this.typeValue = res.data.isShow == 0 ? '否' : '是';
        this.images = 'https://www.wantongkonggu.cn/' + res.data.image;
        this.fileName = res.data.image;
        this.merchantCategoryId = res.data.isShow;
        this.complaintCategorys = res.data.storeType;
      });
    },
    getUserInfo() {
      var userInfo = uni.getStorageSync('userInfo');
      var e = {
        merId: userInfo ? userInfo.merId : '',
        merName: ''
      };
      merlist(e).then((res) => {});
    },
    getType() {
      categorylist().then((res) => {
        this.isType = 2;
        this.showType = true;
        this.columns = [res.rows];
      });
    },
    getestate() {
      estateapppage({ size: 200 }).then((res) => {
        res.data.records.forEach((item) => {
          item.dictValue = item.name;
        });
        this.columns = [res.data.records];
        this.isType = 3;
        this.showType = true;
      });
    },
    addOwner() {
      if (!this.spForm.storeName || !this.typeValue || !this.typeValue1 || !this.spForm.price || !this.spForm.giveIntegral || !this.spForm.canUseIntegral || !this.spForm.stock) {
        uni.showToast({
          icon: 'none',
          title: '请填写完整信息！'
        });
        return;
      }
      var userInfo = uni.getStorageSync('userInfo');
      this.spForm.isShow = this.merchantCategoryId;
      this.spForm.cateId = this.complaintCategorys;
      this.spForm.image = this.fileName;
      this.spForm.isShow = this.stasus;
      productput(this.spForm).then((res) => {
        if (res.code === 200) {
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          uni.$u.toast('操作成功');
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
              success: () => {
                prevPage.onLoad(); // 调用上一页的刷新方法
              }
            });
          }, 1000);
        } else {
          uni.$u.toast(res.msg);
        }
      });
    },
    getTsType({ value }) {
      this.showType = false;
      if (this.isType == 1) {
        this.typeValue = value[0].categoryName;
        this.stasus = value[0].merchantCategoryId;
      } else if (this.isType == 2) {
        this.typeValue1 = value[0].categoryName;
        this.complaintCategorys = value[0].merchantCategoryId;
      }
    },
    getTypelx() {
      this.isType = 1;
      this.showType = true;
      this.columns = [
        [
          { categoryName: '是', merchantCategoryId: '1' },
          { categoryName: '否', merchantCategoryId: '0' }
        ]
      ];
    },
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      console.log(event);
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      // let lists = [].concat(event.file)
      // let fileListLen = this.fileList.length
      // lists.map((item) => {
      // 	this.fileList.push({
      // 		...item,
      // 		status: 'uploading',
      // 		message: '上传中'
      // 	})
      // })
      const result = await this.uploadFilePromise(event.file.url);
      this.images = 'https://www.wantongkonggu.cn/' + result.fileName;
      this.fileName = result.fileName;
      // for (let i = 0; i < lists.length; i++) {
      // 	let item =this.fileList[fileListLen]
      // 	this.fileList.splice(fileListLen, 1, Object.assign(item, {
      // 		status: 'success',
      // 		message: '',
      // 		url: result.url,
      // 		fileName: result.fileName
      // 	}))
      // 	fileListLen++
      // }
      console.log(this.fileList);
    },
    uploadFilePromise(url) {
      const userInfo = uni.getStorageSync('userInfo');
      const token = userInfo ? userInfo.token : '';
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            'Authori-zation': token
          },
          url: 'https://www.wantongkonggu.cn//api/adminApph7/common/upload',
          filePath: url,
          name: 'file',
          formData: {
            user: 'test'
          },
          success: (res) => {
            console.log(res);
            resolve(JSON.parse(res.data));
          }
        });
      });
    }
  }
};
</script>

<style lang="scss">
.textarea_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.input_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}
</style>
